﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace DSA.Shopping_List_Menu
{
	public partial class AddItemPage : PhoneApplicationPage
	{
		private string listname;

		public AddItemPage()
		{
			InitializeComponent();

			SetInputScope(txtQuantity);
		}

		protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
		{
			if (this.NavigationContext.QueryString.ContainsKey("list"))
			{
				listname = this.NavigationContext.QueryString["list"];
			}
		}

		private void SetInputScope(TextBox textBoxControl)
		{
			InputScopeNameValue digitsInputScopeNameValue = InputScopeNameValue.TelephoneNumber;
			textBoxControl.InputScope = new InputScope()
			{
				Names = { new InputScopeName() { NameValue = digitsInputScopeNameValue } }
			};
		}

		private void MaskNumericInput(TextBox textBoxControl, bool allowDecimals)
		{
			string[] invalidCharacters = {"*", "#", ",", "(", ")", "x", "-", "+", " ", "@"};

			if( !allowDecimals)
			{
				invalidCharacters[invalidCharacters.Length - 1] = ".";
			}

			for (int i = 0; i < invalidCharacters.Length; i++)
			{
				textBoxControl.Text = textBoxControl.Text.Replace(invalidCharacters[i], "");
			}

			textBoxControl.SelectionStart = textBoxControl.Text.Length;
		}

		private void txtQuantity_KeyUp(object sender, KeyEventArgs e)
		{
			MaskNumericInput((TextBox)sender, false);
		}

		private void txtQuantity_KeyDown(object sender, KeyEventArgs e)
		{
			MaskNumericInput((TextBox)sender, false);
		}

		private void OkClick(object sender, EventArgs e)
		{
			// Navigate with information
			NavigationService.Navigate(new Uri("/Shopping List Menu/PivotMenu.xaml?name=" + this.txtName.Text +
												"&quant=" + this.txtQuantity.Text +
												"&list=" + this.listname, 
												UriKind.Relative));
		}

		private void CancelClick(object sender, EventArgs e)
		{
			NavigationService.Navigate(new Uri("/Shopping List Menu/PivotMenu.xaml?list=" + this.listname, UriKind.Relative));
		}
		
	}
}